import json
from datetime import datetime

from utils import ask
from utils.dingding import *
from utils.agent import ask_sql
from utils.log_wrapper import log_info,log_debug,log_error

def preprocess_question(question,base_info=None,history=None):
    data = []
    question_append = ""
    for employee in ALL_EMPLOYEES:
        if employee in question:
            if {"function_name":"auto_search","name":employee} not in data:
                log_info(f"Find employee name :{employee} in question.")
                data.append({"function_name":"auto_search","name":employee})
                question_append += f" ,{employee}是员工姓名"
    for project in ALL_PROJECTS:
        if project in question:
            if {"function_name":"auto_search","name":project} not in data:
                data.append({"function_name":"auto_search","name":project})
                log_info(f"Find project name :{project} in question.")
                question_append += f" ,{project}是项目名称"
    for department in ALL_DEPARTMENTS:
        if department in question:
            if {"function_name":"auto_search","name":department} not in data:
                data.append({"function_name":"auto_search","name":department})
                log_info(f"Find department name :{department} in question.")
                question_append += f" ,{department}是部门名称"
    # 调用ask_sql自动获取额外信息
    sql_extra_data = ask_sql(question,history=history)
    question_append += f"\n<额外信息>\nSQL查询的参考结果：{sql_extra_data}\n<\额外信息>"
    if len(sql_extra_data)<3:
        query_text_for_text = f"<原始内容>{question}<\原始内容>\n请你帮我提取特定名词，我会去知识库中搜索相关内容。返回python list格式结果，例如：['销售','财务']，注意：进展、进度、情况等通用词语不要提取"
        r = ask(query_text_for_text,history=None)
        # 提取r从[开始到]结束的部分
        if "[" not in r or "]" not in r:
            log_error("Error in preprocess_question")
            return question
        if len(r)<5:
            log_error(f"Error in preprocess_question: len of {r} < 5")
            return question
        r = r[r.find("["):r.find("]") + 1]
        # "["{'function_name': 'get_projectinfo'", " 'name': '盯小语'}", " {'function_name': 'search_database'", " 'keyword': '盯小语进展'}\n"]"
        # ->
        # [{'function_name': 'get_projectinfo', 'name': '盯小语'}, {'function_name': 'search_database', 'keyword': '盯小语进展'}]
        r = r.strip().replace("\n","")
        log_info(f"\t*🧠 智能体摘取关键字:{r}")
        r = r.replace('[','').replace(']','').replace('\'','').replace('\"','').replace(',',' ').replace('，','').replace('。','').split()
        for keyword in r:
            if keyword:
                if {"function_name":"auto_search","name":keyword} not in data:
                    data.append({"function_name":"auto_search","name":keyword})
                    if len(data)>2:
                        break
    question += question_append
    # if data==[] and len(question_append)<100:
    if False:
        # 首先让大模型提取关键词，然后去auto_search
        query_text_for_text = f"<原始内容>{question}<\原始内容>\n请你帮我提取特定名词，我会去知识库中搜索相关内容。返回python list格式结果，例如：['销售','财务']，注意：进展、进度、情况等通用词语不要提取"
        r = ask_qwen(query_text_for_text,history=None)
        # 提取r从[开始到]结束的部分
        if "[" not in r or "]" not in r:
            log_error("Error in preprocess_question")
            return question
        if len(r)<5:
            log_error(f"Error in preprocess_question: len of {r} < 5")
            return question
        r = r[r.find("["):r.find("]") + 1]
        # "["{'function_name': 'get_projectinfo'", " 'name': '盯小语'}", " {'function_name': 'search_database'", " 'keyword': '盯小语进展'}\n"]"
        # ->
        # [{'function_name': 'get_projectinfo', 'name': '盯小语'}, {'function_name': 'search_database', 'keyword': '盯小语进展'}]
        r = r.strip().replace("\n","")
        log_info(f"\t*🧠 智能体摘取关键字:{r}")
        r = r.replace('[','').replace(']','').replace('\'','').replace('\"','').replace(',',' ').replace('，','').replace('。','').split()
        for keyword in r:
            if keyword:
                if {"function_name":"auto_search","name":keyword} not in data:
                    data.append({"function_name":"auto_search","name":keyword})
                    if len(data)>2:
                        break
    log_info(f"# Actions: {data}")
    question += question_append
    log_info(f"# Question: {question}")
    if base_info is None:
        base_info = get_base_info()
    
    output = "<问题>"
    output += str(question)
    output += "<\问题>\n"
    output += "<基础信息>"
    output += str(base_info)
    output += "<\基础信息>\n"
    output += "<外部信息>"
    for _data in data:
        try:
            function_name = _data["function_name"]
            function_result = eval(function_name)(_data)
            function_result_str = json.dumps(function_result,ensure_ascii=False)
            output+=function_result_str+"\n"
        except Exception as e:
            print(f"Error in function_name:{function_name}, input:{_data}, error:{e}")
    output += "<\外部信息>"
    return output

def get_base_info():
    base_info = f"现在是{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, 今天是星期{datetime.now().weekday() + 1}"
    return base_info

def intelligent_agent(question,history=None):
    base_info = get_base_info()
    question_new = preprocess_question(question,base_info,history=history)
    log_info(f"\t*😶 Auto Rethink:{question_new}")
    final_result = ask(question_new,history)
    new_history = history if history else [] + [{"role": "user", "content": question_new}] + [{"role": "assistant", "content": final_result}]
    if len(new_history) > 5:
        new_history = new_history[-5:]
    return final_result, new_history
